package com.jinsp.skinlib;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * Created by luoshuai on 10/27/21
 * <p>
 * 监听activity生命周期并切入系统的view创建过程
 */
public class SkinActivityLifecycleCallback implements Application.ActivityLifecycleCallbacks {

    protected static final Map<Activity, ActivityViewManager> activityViewManagerMap = new WeakHashMap<>(32);

    /**
     * 该created会在activity的onCreate函数内被调用
     *
     * @param activity           当前正要创建的activity
     * @param savedInstanceState 保存数据实例
     */
    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        LayoutInflater layoutInflater = LayoutInflater.from(activity);
        //需要将LayoutInflater中的mFactorySet置为false以便继续使用工厂
        try {
            Field mFactorySet = LayoutInflater.class.getDeclaredField("mFactorySet");
            if (mFactorySet != null) {
                try {
                    mFactorySet.setAccessible(true);
                    mFactorySet.setBoolean(layoutInflater, false);
                    ActivityViewManager activityViewManager = new ActivityViewManager();
                    layoutInflater.setFactory2(activityViewManager);
                    activityViewManagerMap.put(activity, activityViewManager);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        //可见时更新
        ActivityViewManager viewManager = activityViewManagerMap.get(activity);
        if (viewManager != null) {
            if (!viewManager.isResourcesAlreadyUpdate) {
                //刷新页面为新资源
                viewManager.startChange();
            }
        }
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        //移除当前activity对应的换肤view
        activityViewManagerMap.remove(activity).release();
    }
}
